#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import mrget
import pathlib
import strict_portage
from fm_util import Util
from fm_util import CcacheLocalService
from helper_pkg_warehouse import PkgWarehouse


class DynCfgModifier:

    @classmethod
    def update(cls):
        cls._updateMirrors()
        cls._updateCcache()

        def raiseException(s):
            raise Exception(s)
        PkgWarehouse().checkMaintPkgSets(True, raiseException)

    @staticmethod
    def _updateMirrors():
        portageCfgDir = strict_portage.cfg.PortageConfigDir()

        # update /etc/portage/make.conf
        makeConf = portageCfgDir.get_make_conf_obj()
        makeConf.update_var_as_value_set("GENTOO_MIRRORS", mrget.target_urls("mirror://gentoo", protocols=["http", "https", "ftp"], max_count=3))
        makeConf.update_var_as_value_set("RSYNC_MIRRORS", mrget.target_urls("mirror://gentoo-portage", protocols=["rsync"], max_count=3))

        # update /etc/portage/mirrors
        # FIXME: portage's solution is not good
        buf = ""
        for name in ["bittorrent", "gog", "hb", "hf-co", "librungame-repacks", "myabandonware-game"]:           # these are file mirrors
            try:
                mlist = mrget.target_urls("mirror://%s" % (name), protocols=["http", "https", "ftp"], max_count=3)
                if len(mlist) > 0:
                    buf += name + "\t" + " ".join(mlist) + "\n"
            except ValueError:
                pass
        for name in ["github"]:                                                                                 # these are git mirrors
            try:
                mlist = mrget.target_urls("mirror://%s" % (name), protocols=["git", "http", "https"], max_count=3)
                if len(mlist) > 0:
                    buf += name + "\t" + " ".join(mlist) + "\n"
            except ValueError:
                pass
        if buf != "":
            pathlib.Path(portageCfgDir.mirrors_file_path).write_text(buf)
        else:
            Util.forceDelete(portageCfgDir.mirrors_file_path)

    @staticmethod
    def _updateCcache():
        makeConf = strict_portage.cfg.MakeConf()
        valueList = makeConf.get_var("FEATURES", parse=True)

        c = CcacheLocalService()
        if c.is_enabled():
            if "ccache" not in valueList:
                valueList.append("ccache")
                makeConf.set_var("FEATURES", valueList, synthesize=True)
        else:
            if "ccache" in valueList:
                valueList.remove("ccache")
                makeConf.set_var("FEATURES", valueList, synthesize=True)
